<script lang="ts" setup>
import { Dialog } from '@ark-ui/vue/dialog';
import { SegmentGroup } from '@ark-ui/vue/segment-group';
import { ref, onMounted, useTemplateRef, watch } from 'vue';
import { useRouter } from 'vue-router';
import { watchDebounced } from '@vueuse/core';
import { useFetch } from '@/home/hooks/fetch';
import { useI18n } from 'vue-i18n';
import {
  getHistory,
  setHistory,
  addHistory,
  clearHistory,
} from '@/home/utils/search-history';

const open = defineModel<boolean>('open');

const router = useRouter();
const { $fetch } = useFetch();
const { t } = useI18n();

const searchTypeList = [
  {
    text: t('common.searchDialog.searchType1'),
    value: 'journalism',
  },
  {
    text: t('common.searchDialog.searchType2'),
    value: 'repository',
  },
  {
    text: t('common.searchDialog.searchType3'),
    value: 'organization',
  },
  {
    text: t('common.searchDialog.searchType4'),
    value: 'tag',
  },
];

const searchType = ref<'journalism' | 'repository' | 'organization' | 'tag'>('journalism');
const history = ref<string[]>([]);
const query = ref('');
const searchListing = ref<Record<string, any>[]>([]);
const inputRef = useTemplateRef('input');

const getSearchHistory = () => {
  history.value = getHistory();
}

const addSearchHistory = (text: string) => {
  history.value = addHistory(text);
}

const gotoSearch = (text: string) => {
  router.push({
    path: '/search',
    query: {
      type: searchType.value,
      q: text,
    },
  });

  open.value = false;
}

const clearSearchHistory = () => {
  clearHistory();
  history.value = [];
}

const removeHistoryByIndex = (index: number) => {
  history.value.splice(Math.abs(index - history.value.length + 1), 1);
  setHistory(history.value);
}

const getSearch = async () => {
  if (!query.value) {
    searchListing.value = [];
    return;
  }

  const { isSuccess, data } = await $fetch('/esInfoProduct/smallWindowQueryProduct', {
    method: 'post',
    data: {
      productType: searchType.value,
      keyWords: query.value,
      pageNum: 1,
      pageSize: 5,
    },
  });

  if (isSuccess) {
    searchListing.value = data?.records ?? [];
  }
}

const submitSearch = () => {
  if (!query.value) {
    return;
  }

  addSearchHistory(query.value);

  const text = query.value;

  query.value = '';
  searchListing.value = [];

  // 跳转到搜索结果页
  gotoSearch(text);
}

watchDebounced(query, () => getSearch(), { debounce: 500 });
watch(searchType, () => getSearch());

watch(open, (value) => {
  if (value) {
    getSearchHistory();
  }
});

onMounted(() => {
  getSearchHistory();
});
</script>

<template>
  <ClientOnly>
    <Teleport to="body">
      <div class="search-dialog">
        <Dialog.Root v-model:open="open" :initial-focus-el="(() => inputRef as HTMLElement)">
          <Dialog.Backdrop class="search-dialog-backdrop fixed bottom-0 left-0 right-0 top-0 z-99999 bg-black/30" />
          <Dialog.Positioner class="search-dialog-container fixed bottom-0 left-0 right-0 top-0 z-999999">
            <Dialog.Content class="absolute left-50% top-15% w-640 translate-x--50% border-1 border-#ebebeb rounded-6 border-solid bg-white p-20 text-#8b8b8b">
              <SegmentGroup.Root v-model="searchType" orientation="horizontal" class="flex gap-x-16">
                <SegmentGroup.Item
                  v-for="item in searchTypeList"
                  :key="item.value"
                  :value="item.value"
                  class="block cursor-pointer border-1 border-#FAFAFA rounded-4 border-solid bg-#FAFAFA px-12 py-3 text-12 leading-16 data-[state=checked]:(border-#345DE2 bg-[rgba(52,93,226,0.04)] text-#345DE2)"
                >
                  <SegmentGroup.ItemText>{{ item.text }}</SegmentGroup.ItemText>
                  <SegmentGroup.ItemControl />
                  <SegmentGroup.ItemHiddenInput />
                </SegmentGroup.Item>
              </SegmentGroup.Root>

              <form @submit.prevent="submitSearch">
                <div class="mt-16 flex-y-center">
                  <input
                    v-model.trim="query"
                    class="h-32 flex-grow border-none bg-transparent text-18 placeholder:(text-#8b8b8b) focus-visible:outline-unset"
                    :placeholder="$t('common.searchDialog.inputPlaceholder')"
                    ref="input"
                  >
                  <button type="submit" class="ml-16 h-32 w-16 flex-shrink-0 bg-transparent text-#ADADAD">
                    <span class="i-icons:arrow-right-1 block size-full"></span>
                  </button>
                </div>
              </form>

              <template v-if="history.length">
                <hr class="mt-16 h-1 border-#F7F7F7">

                <div class="mt-16">
                  <div class="flex-y-center justify-between">
                    <div class="text-12 text-#adadad leading-20">{{ $t('common.searchDialog.history') }}</div>
                    <button type="button" class="bg-transparent text-12 text-#345DE2 leading-20" @click="clearSearchHistory">{{ $t('common.searchDialog.clear') }}</button>
                  </div>
                  <ul class="mt-8">
                    <li
                      class="group ml--6 h-32 flex-y-center justify-between rounded-4 pl-6 text-14 leading-32 hover:(bg-#F7F7F7)"
                      v-for="(item, index) in [...history].reverse()" :key="`${index}-${item}`"
                    >
                      <button type="button" class="flex-grow truncate bg-transparent text-left" @click="gotoSearch(item)">{{ item }}</button>
                      <div class="ml-16 mr-8 size-16 flex-shrink-0">
                        <button type="button" class="hidden size-full bg-transparent text-#ADADAD group-hover:(block)" @click="removeHistoryByIndex(index)">
                          <span class="i-icons:close block size-full"></span>
                        </button>
                      </div>
                    </li>
                  </ul>
                </div>
              </template>

              <template v-if="searchListing.length">
                <hr class="mt-16 h-1 border-#F7F7F7">

                <div class="mt-16">
                  <div class="text-12 text-#adadad leading-20">{{ $t('common.searchDialog.content') }}</div>
                  <ul class="mt-8">
                    <li
                      class="ml--6 h-32 rounded-4 pl-6 text-14 leading-32 hover:(bg-#F7F7F7)"
                      v-for="item in searchListing" :key="item.productId"
                    >
                      <template v-if="searchType === 'journalism'">
                        <!-- eslint-disable-next-line vue/no-v-text-v-html-on-component, vue/no-v-html -->
                        <RouterLink :to="`/explore/journalism/detail/${item.productId}`" v-html="item.productName" class="block size-full flex-grow truncate bg-transparent" target="_blank" />
                      </template>
                      <template v-else-if="searchType === 'tag'">
                        <!-- eslint-disable-next-line vue/no-v-text-v-html-on-component, vue/no-v-html -->
                        <RouterLink :to="`/tag/${item.productId}`" v-html="item.productName" class="block size-full flex-grow truncate bg-transparent" target="_blank" />
                      </template>
                      <template v-else>
                        <!-- eslint-disable-next-line vue/no-v-html -->
                        <a :href="item.productUrl" v-html="item.productName" class="block size-full flex-grow truncate bg-transparent" target="_blank">
                        </a>
                      </template>
                    </li>
                  </ul>
                </div>
              </template>
            </Dialog.Content>
          </Dialog.Positioner>
        </Dialog.Root>
      </div>
    </Teleport>
  </ClientOnly>
</template>

<style lang="scss" scoped>
.search-dialog-container {
  &:deep() {
    em {
      color: #345de2;
      font-style: normal;
    }
  }
}
</style>
